import eventlet
eventlet.monkey_patch()
from app.routes.video_player import socketio
import os
from datetime import timedelta
from flask import request
from app import create_app, db


app = create_app()

# 添加静态资源缓存控制
@app.after_request
def add_cache_headers(response):
    if request.path.startswith('/static/'):
        # 拆分URL路径，获取文件扩展名
        path_parts = request.path.split('.')
        if len(path_parts) > 1:
            ext = path_parts[-1].lower()
            
            # 为不同类型的静态资源设置不同的缓存时间
            if ext in ['js', 'css']:
                # JS和CSS文件缓存2天
                max_age = timedelta(days=2).total_seconds()
            elif ext in ['png', 'jpg', 'jpeg', 'gif', 'ico']:
                # 图片文件缓存3天
                max_age = timedelta(days=3).total_seconds()
            elif ext in ['mp3', 'wav', 'ogg']:
                # 音频文件缓存7天
                max_age = timedelta(days=7).total_seconds()
            elif ext in ['mp4', 'webm']:
                # 视频文件缓存7天
                max_age = timedelta(days=7).total_seconds()
            else:
                # 其他静态资源默认缓存1天
                max_age = timedelta(days=1).total_seconds()
            
            # 设置缓存头
            response.cache_control.max_age = max_age
            response.cache_control.public = True
            response.cache_control.must_revalidate = False
            
            # 添加ETag支持
            response.add_etag()
            response.make_conditional(request)
    
    return response

with app.app_context():
    db.create_all()
    print("✅ 数据库表结构初始化成功")
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

if __name__ == '__main__':
    socketio.run(
        app,
        host='0.0.0.0',
        port=5009,
        debug=False
    )
    
